﻿var zombies = zombies || {};
var windowURL = window.URL || window.webkitURL;

zombies.Advertise = function () {
    var self = this;

    self.Logged = ko.observable();
    self.Loaded = ko.observable(true);
    self.AdvComments = ko.observableArray();
    self.AdvImages = ko.observableArray();
    self.AdvMedias = ko.observableArray();
    self.IsVideo = ko.observable(false);
    self.VideoLink = ko.observable();
    self.IsFlash = ko.observable(false);
    self.FlashLink = ko.observable();
    self.IsImage = ko.observable(false);

    self.IsMember = ko.observable(false);
    self.IsLiked = ko.observable(false);
    self.IsSubcribe = ko.observable(false);

    self.UsId = ko.observable(-1);
    self.UsType = ko.observable('none');

    self.AdvId = ko.observable();
    self.Title = ko.observable();
    self.Publisher = ko.observable();
    self.DateCreated = ko.observable();
    self.Description = ko.observable();
    self.Views = ko.observable();
    self.Likes = ko.observable();
    self.LinkPub = ko.observable();
    self.Type = ko.observable();

    self.Content = ko.observable();

    self.Comment = function () {
        $.ajax({
            type: "POST",
            url: "/api/AdvDetails/SendComment",
            contentType: "application/json",
            data: ko.toJSON({ Id: self.AdvId, Comment: self.Content }),
            dataType: 'json'
        }).done(function (item) {
            if (typeof item != "undefined") {
                self.AdvComments.unshift(new zombies.AdvComment(item, self.UsId(), self.UsType()));
                self.Content("");
            }
            else {
                toastr.error('Please Login first');
                self.Logged(false);
            }
        });
    };

    self.DeleteComment = function (item) {
        //$.confirm({
        //    text: "Bạn chắc chắn muốn xóa bình luận này",
        //    title: "<strong>Xác nhận xóa bình luận</strong>",
        //    confirm: function (button) {
        //        $.ajax({
        //            type: "DELETE",
        //            url: "/api/AdvDetails/DeleteComment/" + item.CommentId,
        //            success: function (data) {
        //                self.AdvComments.remove(item);
        //                toastr.success("Xóa bình luận thành công!");
        //            },
        //            error: function (error) {
        //                toastr.error("Xóa bình luận thất bại!");
        //            }
        //        });
        //    },
        //    confirmButton: "Xác Nhận Xóa",
        //    cancelButton: "Hủy"
        //});

        $.ajax({
            type: "DELETE",
            url: "/api/AdvDetails/DeleteComment/" + item.CommentId,
            success: function (data) {
                self.AdvComments.remove(item);
                toastr.success("Xóa bình luận thành công!");
            },
            error: function (error) {
                toastr.error("Xóa bình luận thất bại!");
            }
        });
    };

    self.DoLike = function () {
        $(".like-action").toggleClass("off");

        $.ajax({
            url: '/api/AdvDetails/DoLike/' + self.AdvId(),
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (id) {
            self.IsLiked(!self.IsLiked());
            if (self.IsLiked()) {
                self.Likes(self.Likes() + 1);
            }
            else {
                self.Likes(self.Likes() - 1);
            }
        });
    };

    self.DoSubcribe = function () {
        $.ajax({
            url: '/api/AdvDetails/DoSubcribe/' + self.AdvId(),
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (id) {
            self.IsSubcribe(!self.IsSubcribe());
        });
    };
};

zombies.AdvComment = function (item, UsId, UsType) {
    var self = this;
    self.CommentId = item.CommentId;
    self.Content = item.Content;
    self.HtmlTag = item.Name + "<img src='../" + item.Avatar + "' />";
    self.DateComment = item.DateComment;

    if (UsId == -1) {
        self.IsOwn = false;
    }
    else {
        if (item.Id == UsId) {
            if (item.Type == UsType) {
                self.IsOwn = true;
            }
            else {
                self.IsOwn = false;
            }
        }
        else {
            self.IsOwn = false;
        }
        //self.IsOwn = item.Id == UsId ? (item.Type == UsType ? true : false) : false;
    }

    if (self.IsOwn) {
        if (UsType == 'Member') {
            self.Link = '../../Member';
        }
        else {
            self.Link = '../../Publisher'
        }
    }
    else {
        self.Link = item.Type == 'Member' ? '../../Home/Member/' + item.Id : '../../Home/Publisher/' + item.Id;
    }
};

zombies.AdvImage = function (item) {
    var self = this;

    self.AdvImageId = item.AdvImageId;
    self.Link = '../' + item.Link;
    self.HtmlTag = "<img src='" + self.Link + "' />";
};

zombies.AdvMedia = function (item) {
    var self = this;

    self.MediaId = item.MediaId;
    self.MediaLink = '../' + item.MediaLink;
};

var isAuthen = function (id) {
    $.ajax({
        url: '/api/AdvDetails/IsAuthen/' + id,
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (tmp) {
        advertiseDetailViewModel.Logged(true);
        advertiseDetailViewModel.UsType(tmp.Type);
        advertiseDetailViewModel.UsId(tmp.UId);
        if (tmp.Type == 'Member') {
            advertiseDetailViewModel.IsMember(true);
            advertiseDetailViewModel.IsLiked(tmp.IsLiked);
            if (tmp.IsLiked) {
                $(".like-action").toggleClass("off");
            }
            advertiseDetailViewModel.IsSubcribe(tmp.IsSubcribe);
        }
    }).fail(function () {
        advertiseDetailViewModel.Logged(false);
    }).always(function () {
        load(advid_tmp);
    });

};

var loadMedia = function (id) {
    advertiseDetailViewModel.AdvMedias.removeAll();
    sliders = [];
    $.ajax({
        url: '/api/AdvDetails/GetMedias/' + id,
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        if (advertiseDetailViewModel.IsImage()) {
            $.each(items, function (idx, item) {
                advertiseDetailViewModel.AdvMedias.push(new zombies.AdvMedia(item));
            });
            $('.slidyContainer').slidy({
                // Options go here, see slidy.js
                // These the defaults so don't only need to be specified if they are changed

                throttle: false, // Set to true, and include jQuery throttle plugin (http://benalman.com/projects/jquery-throttle-debounce-plugin/)
                throttleTime: 500, // number of ms to wait for throttling
                showArrows: true, // Show arrows for next/prev image
                movePrev: 'movePrev', // Div id to use for previous button
                moveNext: 'moveNext', // Div id to use for next button
                useKeybord: true, // use keys defined below to expand / collapse sections
                auto: true,       // Start slideshow automatically
                interval: 4000,     // Time between each slide
                initialInterval: 6000  // Initial interval when page loads

            });
        }
        else if (advertiseDetailViewModel.IsVideo()) {
            advertiseDetailViewModel.VideoLink(items[0].MediaLink);
        }
        else {
            advertiseDetailViewModel.FlashLink(items[0].MediaLink);
        }
    }).error(function () {
        toastr.error('error');
        advertiseDetailViewModel.Loaded(false);
    });
}

var load = function (id) {

    advertiseDetailViewModel.AdvId(id);

    $.ajax({
        type: "GET",
        url: "/api/AdvDetails/GetAdv/" + id,
        contentType: "application/json",
        dataType: 'json'
    }).done(function (item) {
        advertiseDetailViewModel.Title(item.Title);
        advertiseDetailViewModel.Publisher(item.Publisher);
        advertiseDetailViewModel.DateCreated(moment(item.DateCreated).format('LLLL'));
        advertiseDetailViewModel.Description(item.Description);
        advertiseDetailViewModel.Views(item.Views);
        advertiseDetailViewModel.Likes(item.Likes);
        advertiseDetailViewModel.LinkPub('../../Home/channel/' + item.PubId);
        advertiseDetailViewModel.Type(item.Type);
        if (item.Type == "Video") {
            advertiseDetailViewModel.IsVideo(true);
        }
        else if (item.Type == "Flash") {
            advertiseDetailViewModel.IsFlash(true);
        }
        else {
            advertiseDetailViewModel.IsImage(true);
        }
    }).error(function () {
        advertiseDetailViewModel.Loaded(false);
    }).always(function () {
        loadMedia(id);
    });

    advertiseDetailViewModel.AdvComments.removeAll();
    $.ajax({
        url: '/api/AdvDetails/GetComments/' + id,
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        $.each(items, function (idx, item) {
            advertiseDetailViewModel.AdvComments.push(new zombies.AdvComment(item, advertiseDetailViewModel.UsId(), advertiseDetailViewModel.UsType()));
        });
    }).error(function () {
        advertiseDetailViewModel.Loaded(false);
    });

    advertiseDetailViewModel.AdvImages.removeAll();
    $.ajax({
        url: '/api/AdvDetails/GetImages/' + id,
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        $.each(items, function (idx, item) {
            advertiseDetailViewModel.AdvImages.push(new zombies.AdvImage(item));
        });
    }).error(function () {
        advertiseDetailViewModel.Loaded(false);
    });
};

var advertiseDetailViewModel;
var advid_tmp = document.URL.split('/').pop();
$(document).ready(function () {
    advertiseDetailViewModel = new zombies.Advertise();
    isAuthen(advid_tmp);
    ko.applyBindings(advertiseDetailViewModel, document.getElementById("my-container"));
});